import django.http as http
import django.shortcuts as shortcuts
from django.template import RequestContext
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.core.urlresolvers import reverse

import django_comments.models as models
import django_comments.forms as forms

def comment(request,  content_type,  object_id):
    if community_helpers.get_logged_user(request):
        target_model = ContentType.objects.get(id = content_type)
        template_name = 'comments/comment_' + str(target_model.model_class().__name__).lower() + '.html'
    else:
        template_name = 'util/error.html'
    return shortcuts.render_to_response(
            template_name, 
            {'node':node, 'confirmation':confirmation,  'content_type':content_type,  'object_id':object_id}, 
            context_instance = RequestContext(request), 
    )

def ajax_comment(request,  content_type,  object_id, mode = None, parent = None):
    user = request.user
    
    if user and request.POST:
        comment = request.POST.get('comment', '')
        target_model = ContentType.objects.get(id = content_type)
        target_object = target_model.model_class().objects.get(id = object_id)
        models.Comment.objects.add_comment(user, target_object, comment, parent)
        template_name = "django_comments/standard_comment_list.html"
    return shortcuts.render_to_response(
            template_name, 
            {'node':target_object, 'content_type':content_type,  'object_id':object_id,  'comments':target_object.comments.all(),  'mode':mode}, 
            context_instance = RequestContext(request), 
    )

def edit_comment(request,  comment_id):
    user = community_helpers.get_logged_user(request)
    
    if user:
        comment = models.Comment.objects.get(id = comment_id)
        EditCommentForm = forms.build_edit_comment_form(comment)
        if request.POST:
            form = EditCommentForm(request.POST,  request.FILES)
            if form.is_valid():
                form.handle_edit(user, comment)
                return http.HttpResponseRedirect(reverse('content-redirect-by-id',  args=[comment.content_type.id,  comment.object_id]))
        else:
            form = EditCommentForm()
    return shortcuts.render_to_response(
        'comments/edit_comment.html', 
        {'form':form,  'comment':comment,  'node_content_type':comment.content_type.id,  'node_object_id':comment.object_id}, 
        context_instance = RequestContext(request)
    )
